import {
    waitCover, CDNURL, codeTranslate, handleErr
} from './core';

const $ = window.$;

export default function ($parent, options = {}) {
    $parent = $($parent);
    // 不存在上传占位div， 或者class包含disabled
    if (!$parent.length) {
        return;
    }

    const PERCENT_TPL = '上传中 <span class="percent">0%</span>';
    const TRANSLATE_CODE_TPL = '视频转码中';
    // const DEFAULT_COVER = '';

    const TPL = `${'<div class="video-upload-btn-warp">'
        + '<div class="video-upload-btn">'
        + '<div>'
        + '<i class="wptFont-video-icon"></i>'
        + '<div>15秒视频</div>'
        + '</div>'
        + '</div>'
        + '</div>'
        + '<div class="video-uploading" >'
        + '<div class="mask">'
        + '<div>'
        + '<i class="wptFont-video-icon"></i>'
        + '<div class="video-uploading-tips">'}${
        PERCENT_TPL
    }</div>`
        + '</div>'
        + '</div>'
        + '<div class="video-play"></div>'
        + '</div>'
        + '<div class="delete"></div>';

    // 重置上传控件
    const resetUploader = function () {
        WPT.uploadVideo.reset && WPT.uploadVideo.reset();
    };

    // 模板渲染
    function renderTPL() {
        $parent.html(TPL);
    }

    /**
     * [setPoster 设置封面图]
     * @method setPoster
     * @param  {[type]}  videoPoster [description]
     */
    function setPoster(videoPoster) {
        videoPoster = videoPoster
            // eslint-disable-next-line max-len
            || '';
        $parent.find('.video-uploading').css('background-image', `url(${videoPoster})`);
    }

    // 视频上传完成
    function videoUploadDone(key) {
        // 隐藏上传遮罩，显示delete
        $parent.find('.video-uploading-tips').html(TRANSLATE_CODE_TPL);
        $('input[name="video"]').val(key);
        options.success && options.success(key);
        // 等待截图完成
        waitCover(
            key,
            CDNURL,
            (src) => {
                setPoster(src);
                $parent.removeClass('progress').addClass('done');
                $parent.find('.video-uploading-tips').html(PERCENT_TPL);
            },
            () => {
                setPoster('');
            }
        );
    }

    // 删除视频
    function deleteVideo() {
        resetUploader();
        const key = $('input[name="video"]').val();
        $('input[name="video"]').val('');

        $parent.removeClass('done progress').data('src', '');
        $parent
            .find('video')
            .hide()
            .attr('src', '');

        setPoster();
        options.remove && options.remove(key);
    }

    const OPTIONS = {
        // 事件回调配置FilesAdded、UploadProgress、FileUploaded
        onStart(nativeFiles, uploader) {
            if (nativeFiles.length > 1) {
                return WPT.Modal.alert('只能选择一个视频文件', { style: { color: '#AB3B3A' } });
            }

            const nativeFile = nativeFiles[0];
            // 视频最大限制，因为iPhone有视频自动压缩功能，因此限制其大小为10m
            const limtMax = $.os.ios ? 10 : 40;
            const limtMin = 0.1;

            const nativeFileSize = nativeFile.size / 1024 / 1024;

            if (nativeFileSize < limtMin) {
                resetUploader();
                return WPT.Modal.alert(`视频大小不能小于${limtMin}M`, { style: { color: '#AB3B3A' } });
            }

            if (nativeFileSize > limtMax) {
                resetUploader();
                return WPT.Modal.alert(`视频大小不能超过${limtMax}M`, { style: { color: '#AB3B3A' } });
            }

            // 开始上传
            uploader.start();

            // 元素上传中
            $parent.find('.percent').val('0%');

            // 保存视频地址
            const src = URL.createObjectURL(nativeFile);
            renderTPL();
            $parent.data('src', src);

            // 不允许保存草稿/下一步
            $parent
                .removeClass('done')
                .addClass('progress')
                .data('done', 'false');
            return '';
        },
        onProgress(percent) {
            if (!$parent.addClass('progress')) {
                renderTPL();
                // 不允许保存草稿/下一步
                $parent
                    .removeClass('done')
                    .addClass('progress')
                    .data('done', 'false');
            }
            // 显示进度
            $parent.find('.percent').text(`${percent}%`);
        },
        onSuccess(key) {
            codeTranslate(key);

            // 可以进行下一步
            $parent
                .data('done', 'true')
                .data('key', key)
                .data('src', CDNURL + key);
            // 存储key，上传结束
            videoUploadDone(key);
        },
        onFail(err, errTip) {
            const tips = handleErr(err, errTip);
            // WPT.Modal.alert(tips, function() {
            //     deleteVideo();
            // });
            WPT.Modal.alert(tips, {
                style: { color: '#AB3B3A' },
                callback() {
                    deleteVideo();
                }
            });
        },
    };

    // 初始化
    function init() {
        // 渲染模板
        renderTPL();

        const videoSrc = $parent.data('src');
        const videoPoster = $parent.data('poster');
        $parent.data('src', videoSrc);

        // 添加默认poster
        setPoster('');

        if (videoSrc) {
            $parent
                .addClass('done')
                .find('video')
                .attr('src', videoSrc);
            setPoster(videoPoster);
        }

        // 事件绑定
        $parent
            .on('click', '.delete', () => {
                // 移除key
                deleteVideo();
            })
            .on('click', '.video-uploading', function () {
                // 播放视频
                WPT && WPT.playVideo && WPT.playVideo($(this).parent(), WPT.getVideoSrc($(this).parent()));
            })
            .on('click', '.video-upload-btn', () => {
                // 上传视频
                WPT.uploadVideo(OPTIONS);
            });
    }

    // 初始化
    init();
}
